import React, { Component } from "react";
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
  AsyncStorage,
  ScrollView,
  KeyboardAvoidingView,
  Keyboard,
  Animated
} from "react-native";
import { wp, hp } from "../Style/responsive";
import Header from "../Components/Header";
import { colors } from "../Style/Colors";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import Quote from "../Components/Quote";
import { toLogin } from "./../api/config";
import { setFontSize } from "../Components/SetSize";

const IMAGE_HEIGHT = 80;
const IMAGE_HEIGHT_SMALL = 50;

export class DoctorLogin extends Component {
  state = {
    passwordTextEntry: true,
    username: "",
    password: "",
    isLoading: false,
    error: "",
    showMessage: false,
    message: "",
    imageHeight: new Animated.Value(IMAGE_HEIGHT)
  };

  onPasswordTextEntry = () => {
    this.setState(prevState => ({
      passwordTextEntry: !prevState.passwordTextEntry
    }));
  };

  componentDidMount() {
    this.keyboardDidShowSub = Keyboard.addListener(
      "keyboardDidShow",
      this.keyboardDidShow
    );
    this.keyboardDidHideSub = Keyboard.addListener(
      "keyboardDidHide", //keyboardWillHide
      this.keyboardDidHide
    );
  }

  componentWillUnmount() {
    this.keyboardDidShowSub.remove();
    this.keyboardDidHideSub.remove();
  }

  keyboardDidShow = event => {
    Animated.timing(this.state.imageHeight, {
      duration: 350,
      toValue: IMAGE_HEIGHT_SMALL
    }).start();
  };

  keyboardDidHide = event => {
    Animated.timing(this.state.imageHeight, {
      duration: 350,
      toValue: IMAGE_HEIGHT
    }).start();
  };

  onLogin = () => {
    const { username, password } = this.state;
    this.setState({ showMessage: false });

    if (!username && !password) {
      this.setState({
        message: "Username and Password should not be empty",
        showMessage: true
      });
    } else {
      this.setState({ isLoading: true });
      toLogin(username, password, 1)
        .then(res => {
          this.setState({ isLoading: false });

          if (res.Code) {
            AsyncStorage.setItem("user-data", JSON.stringify(res)).then(() => {
              AsyncStorage.setItem("loggedin-user", "doctor").then(() => {
                this.props.navigation.navigate("FetchData");
              });
            });
          } else {
            this.setState({
              message: "Username or Password is wrong!",
              showMessage: true
            });
          }
        })
        .catch(e => {
          this.setState({
            message: "Could not connect server!",
            showMessage: true,
            isLoading: false
          });
        });
    }
  };

  onChangeUsernameHandle = username => {
    this.setState({
      username: username
    });
  };
  onChangePasswordHandle = password => {
    this.setState({ password });
  };

  render() {
    const { passwordTextEntry, showMessage, message } = this.state;

    return (
      <KeyboardAvoidingView
        keyboardVerticalOffset={20}
        behavior="padding"
        style={styles.container}
      >
        <Header text="DOCTOR LOGIN" isBack={true} />
        <ScrollView style={{ flex: 1 }}>
          <Quote />
          <View style={styles.loginWrapper}>
            <View style={styles.userNameWrapper}>
              <TextInput
                autFocus={true}
                style={styles.textInput}
                returnKeyType={"next"}
                placeholder="USERNAME"
                onChangeText={username => this.onChangeUsernameHandle(username)}
                value={this.state.username}
                autoCapitalize="characters"
                onSubmitEditing={() => {
                  this.passwordTextInput.focus();
                }}
                blurOnSubmit={false}
              />
            </View>
            <View style={styles.passwordWrapper}>
              <TextInput
                secureTextEntry={passwordTextEntry}
                style={[styles.textInput, { flex: 1 }]}
                placeholder="PASSWORD"
                onChangeText={password => this.onChangePasswordHandle(password)}
                value={this.state.password}
                ref={input => {
                  this.passwordTextInput = input;
                }}
                onSubmitEditing={this.onLogin}
              />
              <Icon
                onPress={this.onPasswordTextEntry}
                style={styles.icon}
                name={passwordTextEntry ? "eye-off" : "eye"}
                color={colors.primaryColor}
                size={20}
              />
            </View>
            <TouchableOpacity
              activeOpacity={0.8}
              onPress={this.onLogin}
              style={styles.buttonWrapper}
            >
              {this.state.isLoading ? (
                <ActivityIndicator size="small" color={colors.whiteColor} />
              ) : (
                <Text style={styles.loginText}>LOGIN</Text>
              )}
            </TouchableOpacity>
          </View>
          {showMessage && (
            <View style={styles.messageWrapper}>
              <Text style={styles.messageText}>{message}</Text>
            </View>
          )}
        </ScrollView>
      </KeyboardAvoidingView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  loginWrapper: {
    backgroundColor: colors.whiteColor,
    elevation: 1,
    borderWidth: 0.4,
    marginTop: 30,
    paddingHorizontal: 20,
    paddingVertical: 10,
    width: wp("80%"),
    alignSelf: "center",
    borderColor: colors.lightGrey,
    shadowColor: "black",
    shadowOffset: { height: 1, width: 0 },
    shadowOpacity: 0.5
  },
  userNameWrapper: {
    borderBottomWidth: 1,
    marginVertical: 10,
    borderBottomColor: colors.primaryColor,
    paddingVertical: 14
  },
  textInput: {
    fontSize: hp("2%")
  },
  passwordWrapper: {
    flexDirection: "row",
    justifyContent: "space-between",
    borderBottomWidth: 1,
    marginVertical: 10,
    alignItems: "center",
    borderBottomColor: colors.primaryColor,
    paddingVertical: 14
  },
  icon: {
    marginHorizontal: 8
  },
  buttonWrapper: {
    backgroundColor: colors.primaryColor,
    padding: 20,
    alignItems: "center",
    justifyContent: "center",
    marginVertical: 20
  },
  loginText: {
    color: colors.whiteColor,
    fontSize: setFontSize("2.2", "2")
<<<<<<< HEAD
  },
  messageWrapper: {
    justifyContent: "center",
    alignItems: "center",
    marginTop: 8
  },
  messageText: {
    fontSize: 16,
    color: "red"
  },
  logoWrapper: {
    alignItems: "center"
  },
  img: {
    resizeMode: "contain"
  },
  quote: {
    fontSize: setFontSize("2.4", "2"), //2.4 //2
    fontWeight: "bold",
    color: "#333"
=======
>>>>>>> 503b0544130247b48d86f53bc47ed722f01e5c05
  }
});

export default DoctorLogin;
